package com.lenovo.smarttraffic.ui.activity.stage6;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.ParkBean;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import butterknife.BindView;

public class PayCenterActivity extends BaseActivity {

    public static WeakReference<PayCenterActivity> activity;

    public static List<ParkBean.ROWSDETAILBean> list = new ArrayList<>();

    public static int pos = 0;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbar_title;

    @BindView(R.id.map_parent)
    LinearLayout map_parent;
    @BindView(R.id.map_view)
    MapView mMapView;
    @BindView(R.id.line_parent)
    LinearLayout line_parent;
    @BindView(R.id.start_sp)
    Spinner start_sp;
    @BindView(R.id.end_sp)
    Spinner end_sp;
    @BindView(R.id.find_tv)
    TextView find_tv;
    @BindView(R.id.line_tv)
    TextView line_tv;

    @BindView(R.id.listView)
    ListView listView;


    @BindView(R.id.info_parent)
    LinearLayout info_parent;
    @BindView(R.id.name_tv)
    TextView name_tv;
    @BindView(R.id.type_ic)
    View type_ic;
    private TextView type_tv, loc_tv, distant_tv, money_tv, count_tv, money_tv2;

    @BindView(R.id.guide_parent)
    LinearLayout guide_parent;
    @BindView(R.id.start_tv)
    TextView start_tv;
    @BindView(R.id.end_tv)
    TextView end_tv;
    @BindView(R.id.time_tv)
    TextView time_tv;
    @BindView(R.id.distant_tv2)
    TextView distant_tv2;

    @BindView(R.id.start_tv2)
    TextView start_tv2;
    @BindView(R.id.line_lv)
    ListView line_lv;

    private AMap aMap;

    private Bundle savedInstanceState;

    private int images[] = {R.mipmap.marker_one, R.mipmap.marker_second, R.mipmap.marker_thrid, R.mipmap.marker_forth};

    private LatLng latLng = new LatLng(39.941853, 116.385307);

    private String name = "";

    private DrivePath drivePath;

    private LatLng oldlanlan;

    private String start, end;

    @Override
    protected int getLayout() {
        return R.layout.activity_pay_center;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = new WeakReference<>(this);

        this.savedInstanceState = savedInstanceState;

        type_tv = findViewById(R.id.type_tv);
        loc_tv = findViewById(R.id.loc_tv);
        distant_tv = findViewById(R.id.distant_tv);
        money_tv = findViewById(R.id.money_tv);
        count_tv = findViewById(R.id.count_tv);
        money_tv2 = findViewById(R.id.money_tv2);

        toolbar.setNavigationOnClickListener(v -> {
            if (info_parent.getVisibility() == View.VISIBLE) {
                showView(1);
            } else if (guide_parent.getVisibility() == View.VISIBLE) {
                showView(3);
            } else finish();
        });

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else initMap();

        HttpUtils.post("get_park", new HttpUtils().add("UserName", MainActivity.userName), response -> {
            list = new Gson().fromJson(response.toString(), ParkBean.class).getROWS_DETAIL();
            Collections.sort(list, (o1, o2) -> Utils.parseInt(o1.getDistance()) - Utils.parseInt(o2.getDistance()));

            listView.setAdapter(new PayCenterAdapter());
        });
    }

    private void initMap() {
        try {
            mMapView.onCreate(savedInstanceState);
            aMap = mMapView.getMap();

            aMap.setOnMarkerClickListener(marker -> {
                ToastUtils.showToast(this, "定位到什刹海");
                return true;
            });

            Random random = new Random();
            String v1 = "39.9";
            String v2 = "116.3";

            HttpUtils.post("get_park", new HttpUtils().add("UserName", MainActivity.userName), response -> {
                list = new Gson().fromJson(response.toString(), ParkBean.class).getROWS_DETAIL();
                Collections.sort(list, (o1, o2) -> Utils.parseInt(o1.getDistance()) - Utils.parseInt(o2.getDistance()));
                LatLng latLng = new LatLng(Double.parseDouble(v1 + random.nextInt(99)), Double.parseDouble(v2 + random.nextInt(99)));

                listView.setAdapter(new PayCenterAdapter());

                aMap.clear();
                for (int i = 0; i < 3; i++) {
                    aMap.addMarker(new MarkerOptions().position(latLng).title("什刹海").snippet("")
                            .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                    .decodeResource(getResources(), images[i]))).draggable(false));
                }
            });
        } catch (Throwable t) {
            t.printStackTrace();
            ToastUtils.showToast(this, "高德地图初始化失败\n" + t.getMessage());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initMap();
            } else {
                ToastUtils.showToast(this, "存储权限未授予");
            }
        }
    }

    public void showView(int which) {
        if (which == 1) {
            toolbar_title.setText("用户停车");
            info_parent.setVisibility(View.GONE);
            map_parent.setVisibility(View.VISIBLE);


        } else if (which == 2) {
            toolbar_title.setText("停车场详情");
            info_parent.setVisibility(View.VISIBLE);
            map_parent.setVisibility(View.GONE);

            ParkBean.ROWSDETAILBean bean = list.get(pos);
            name_tv.setText(bean.getParking_name());
            type_ic.setBackgroundResource(bean.getOpen_type().equals("对外开放") ? R.mipmap.status_open : R.mipmap.status_close);
            type_tv.setText(bean.getOpen_type());
            loc_tv.setText(bean.getParking_address());
            distant_tv.setText(bean.getDistance() + "米");

            int moneyPerHour = Utils.parseInt(bean.getCharging_reference().substring(3, bean.getCharging_reference().length() - 1));
            money_tv.setText(moneyPerHour + "元/小时");
            count_tv.setText(bean.getFree_parking_number() + "个/" + bean.getTotal_parking_number());
            money_tv2.setText(bean.getCharging_reference() + "，最高" + bean.getPayment_method() + "元/天");
        } else if (which == 3) {
            toolbar_title.setText("离线地图");
            map_parent.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            line_parent.setVisibility(View.VISIBLE);
            guide_parent.setVisibility(View.GONE);


            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
            MarkerOptions markerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.mipmap.location)).position(latLng).draggable(false);
            aMap.addMarker(markerOptions);
            ToastUtils.showToast(this, "已经定位到" + latLng.toString() + list.get(pos).getParking_name());

            ArrayList<String> stop = new ArrayList<>();
            stop.add("窦官站");
            stop.add("下麦西站");
            stop.add("观山湖公园站");
            stop.add("雅关站");
            stop.add("北京路站");

            start_sp.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stop));
            start_sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    start = start_sp.getSelectedItem().toString();

                    ArrayList stopC = (ArrayList<String>) stop.clone();
                    stopC.remove(position);
                    end_sp.setAdapter(new ArrayAdapter<String>(PayCenterActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, stopC));
                    //修改经纬度
                    Double lat = Double.valueOf(String.format(Locale.CHINA, "%.2f", latLng.latitude) + (new Random().nextInt(99) + 10));
                    Double log = Double.valueOf(String.format(Locale.CHINA, "%.2f", latLng.longitude) + (new Random().nextInt(99) + 10));
                    //重新绘制
                    doDraw(new LatLng(lat, log));
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
            end_sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    end = end_sp.getSelectedItem().toString();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });

            find_tv.setOnClickListener(v -> {
                if (name.equals(start_sp.getSelectedItem().toString())) {
                    doDraw(oldlanlan);
                } else {
                    Double lat = Double.valueOf(String.format(Locale.CHINA, "%.2f", latLng.latitude) + (new Random().nextInt(99) + 10));
                    Double log = Double.valueOf(String.format(Locale.CHINA, "%.2f", latLng.longitude) + (new Random().nextInt(99) + 10));
                    LatLng latLng = new LatLng(lat, log);
                    doDraw(latLng);
                    oldlanlan = latLng;
                }
                name = start_sp.getSelectedItem().toString();

                line_tv.setVisibility(View.VISIBLE);
            });
            line_tv.setOnClickListener(v -> {
                showView(4);
            });
        } else {
            toolbar_title.setText("路线指南");
            guide_parent.setVisibility(View.VISIBLE);
            map_parent.setVisibility(View.GONE);
            line_parent.setVisibility(View.GONE);

            int distance = 0;
            for (DriveStep driveStep : drivePath.getSteps()) {
                distance += driveStep.getDistance();
            }

            start_tv.setText(start);
            end_tv.setText(end);

            time_tv.setText((distance / 50) + "分钟");
            distant_tv2.setText((float)(distance / 1000) + "公里");

            start_tv2.setText(start);

            line_lv.setAdapter(new PayCenterAdapter2(drivePath));
        }
    }

    private void doDraw(LatLng latLnga) {
        RouteSearch routeSearch = new RouteSearch(this);

        Double lat = Double.valueOf(String.format(Locale.CHINA, "%.2f", latLnga.latitude) + (new Random().nextInt(99) + 10));
        Double log = Double.valueOf(String.format(Locale.CHINA, "%.2f", latLnga.longitude) + (new Random().nextInt(99) + 10));

        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(new LatLonPoint(latLnga.latitude, latLnga.longitude), new LatLonPoint(lat, log));

        RouteSearch.DriveRouteQuery driveRouteQuery = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_SINGLE_DEFAULT, null, null, "");

        routeSearch.calculateDriveRouteAsyn(driveRouteQuery);
        routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                if (i == 1000) {
                    aMap.clear();
                    aMap.moveCamera(CameraUpdateFactory.newLatLng(latLnga));
                    aMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.mipmap.location)).draggable(false).position(latLnga));

                    drivePath = driveRouteResult.getPaths().get(0);
                    for (DriveStep driveStep : drivePath.getSteps()) {
                        //绘制多条线段
                        PolylineOptions polylineOptions = new PolylineOptions();
                        polylineOptions.width(10);
                        polylineOptions.geodesic(true);
                        polylineOptions.color(0x90000000);
                        for (int i1 = 0; i1 < driveStep.getPolyline().size(); i1++) {
                            LatLonPoint latLonPoint = driveStep.getPolyline().get(i1);
                            polylineOptions.add(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()));
                        }
                        aMap.addPolyline(polylineOptions);
                    }
                }
            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });
    }

    @Override
    public void onBackPressedSupport() {
        if (info_parent.getVisibility() == View.VISIBLE) {
            showView(1);
        } else if (guide_parent.getVisibility() == View.VISIBLE) {
            showView(3);
        } else super.onBackPressedSupport();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mMapView != null) {
            mMapView.onLowMemory();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }
}

class PayCenterAdapter extends BaseAdapter {

    private List<ParkBean.ROWSDETAILBean> data = PayCenterActivity.list;

    public PayCenterAdapter() {
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_user_park, parent, false);
            holder.id_tv = convertView.findViewById(R.id.id_tv);
            holder.info_tv = convertView.findViewById(R.id.info_tv);
            holder.icon = convertView.findViewById(R.id.icon);
            holder.status_tv = convertView.findViewById(R.id.status_tv);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        ParkBean.ROWSDETAILBean bean = data.get(position);
        holder.id_tv.setText("" + (position + 1));
        holder.info_tv.setText(bean.getParking_name() + "\n" +
                "空车位" + bean.getFree_parking_number() + "个 ，" + "停车费" + bean.getCharging_reference().substring(3, bean.getCharging_reference().length() - 1) + "元/小时\n" + bean.getParking_address() + " " + bean.getDistance() + "米");

        boolean full = bean.getFree_parking_number() < 1;
        if (full) {
            holder.info_tv.setClickable(false);
            holder.icon.setClickable(false);
            convertView.setBackgroundColor(Utils.getColor(parent.getContext(), R.color.colorGray));
            holder.icon.setVisibility(View.GONE);
            holder.status_tv.setVisibility(View.VISIBLE);
            holder.status_tv.setText(position % 2 == 0 ? "关闭" : "已满");
        } else {
            convertView.setBackground(null);
            holder.icon.setVisibility(View.VISIBLE);
            holder.status_tv.setVisibility(View.GONE);
            holder.info_tv.setOnClickListener(v -> {
                PayCenterActivity.activity.get().showView(3);
            });
            holder.icon.setOnClickListener(v -> {
                PayCenterActivity.pos = position;
                PayCenterActivity.activity.get().showView(2);
            });
        }

        return convertView;
    }

    static class ViewHolder {
        TextView id_tv, info_tv, status_tv;
        View icon;
    }
}

class PayCenterAdapter2 extends BaseAdapter {

    private DrivePath drivePath;


    public PayCenterAdapter2(DrivePath drivePath) {
        this.drivePath = drivePath;
    }

    @Override
    public int getCount() {
        return drivePath.getSteps().size();
    }

    @Override
    public Object getItem(int position) {
        return drivePath.getSteps().get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_guide_road, parent, false);
            holder.turn_tv = convertView.findViewById(R.id.turn_tv);
            holder.road_tv = convertView.findViewById(R.id.road_tv);
            holder.detail_tv = convertView.findViewById(R.id.detail_tv);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        DriveStep driveStep = drivePath.getSteps().get(position);
        holder.turn_tv.setText(driveStep.getAction());
        holder.road_tv.setText(driveStep.getRoad());
        holder.detail_tv.setText(driveStep.getInstruction());

        return convertView;
    }

    static class ViewHolder {
        TextView turn_tv, road_tv, detail_tv;
    }
}
